﻿Public Class NumberOnlyTextbox
    Inherits TextBox
    Protected m_ctrl As TextBox
    Protected m_throw As KeyEventHandler
    Protected m_AllowMinus As Boolean
    Protected m_AllowDecimalsPoint As Boolean

    Public Sub New(ByRef ctrl As TextBox, ByRef AllowDecimalsPoint As Boolean, ByRef AllowMinus As Boolean, ByRef throwb As KeyEventHandler)
        ' Pass a reference to the textbox
        m_ctrl = ctrl
        ' Are Decimal Points allowed through
        m_AllowDecimalsPoint = AllowDecimalsPoint
        ' Are minus allowed through
        m_AllowMinus = AllowMinus
        ' Pass a reference to the delegate. (This is AddressOf a sub which further process the keypress.)
        m_throw = throwb
        ' Add an handler for the keydown event
        AddHandler m_ctrl.KeyDown, AddressOf M_OnKeyDown
    End Sub

    Protected Sub M_OnKeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs)
        e.SuppressKeyPress = False
        Select Case e.KeyCode
            ' Allow Digit keys through.
            Case Keys.Decimal, Keys.OemPeriod

                If m_AllowDecimalsPoint Then
                    If m_throw IsNot Nothing Then m_throw.Invoke(sender, e)
                End If
            Case Keys.Subtract, Keys.OemMinus
                If m_AllowMinus Then
                    If m_throw IsNot Nothing Then m_throw.Invoke(sender, e)
                End If
            Case Keys.D0 To Keys.D9, Keys.NumPad0 To Keys.NumPad9
                If m_throw IsNot Nothing Then m_throw.Invoke(sender, e)
            Case Keys.Delete, Keys.Back, Keys.Enter, Keys.Return, Keys.Left, Keys.Right, Keys.Tab
                ' Allow "STANDARD" editting keys
                If m_throw IsNot Nothing Then m_throw.Invoke(sender, e)
            Case Else
                ' Supress all other key.
                e.Handled = True
                e.SuppressKeyPress = True
        End Select
    End Sub

    Protected Overrides Sub Finalize()
        ' Remember to remove the handle
        RemoveHandler m_ctrl.KeyDown, AddressOf M_OnKeyDown
        MyBase.Finalize()
    End Sub

    Private Sub InitializeComponent()
        Me.SuspendLayout()
        Me.ResumeLayout(False)

    End Sub
End Class
